<template>
  <div class="ganttContainer">
    <div style="padding-bottom:10px;">
      <el-button style="color:#666;font-size:16px; padding-top:5px; padding-right:20px; font-weight:bold;"  type="text"  @click="openLeftGrid"  :icon="isOpenLeft? 'el-icon-s-fold' : 'el-icon-s-unfold'"></el-button>
      <el-button type="primary"  icon="el-icon-add" size="small"   @click='openAddDialog'>新增计划</el-button>
       <!-- <el-button type="primary"  icon="el-icon-refresh-left" size="small"   @click='undo'>撤回</el-button>
      <el-button type="primary"  icon="el-icon-refresh-right" size="small"  @click='redo'>重做</el-button> -->
      <el-button v-if="zoomInOutModel == 2" type="primary"  icon="el-icon-date" size="small" @click='startZoomIn'>周视图</el-button>
      <el-button  v-if="zoomInOutModel == 1" type="primary"  icon="el-icon-c-scale-to-original" size="small" @click='startZoomOut'>天视图</el-button>
      <el-button v-if="viewModel == 2" type="primary"  icon="el-icon-s-flag" size="small" @click='handleTaskData(1)'>按里程碑展示</el-button>
      <el-button  v-if="viewModel == 1" type="primary"  icon="el-icon-s-operation" size="small" @click='handleTaskData(2)'> 按列表展示 </el-button>
    </div>
    <div ref="gantt" style="height:85vh;"></div>
  </div>
</template>
 
<script>

import {exportBizPlanMilestoneExcel,saveOrUpdateBizPlanMilestone,saveOrUpdateBizPlanMilestoneList,saveBizPlanMilestone,saveBizPlanMilestoneList,deleteBizPlanMilestone,queryBizPlanMilestone,queryBizPlanMilestoneListPage,updateBizPlanMilestone,deleteBizPlanMilestoneList} from '@/api/biz/plan/bizPlanMilestoneApi';
import {exportBizPlanManageExcel,saveOrUpdateBizPlanManage,saveOrUpdateBizPlanManageList,saveBizPlanManage,saveBizPlanManageList,deleteBizPlanManage,queryBizPlanManage,queryBizPlanManageListPage,updateBizPlanManage,deleteBizPlanManageList} from '@/api/biz/plan/bizPlanManageApi';
import {gantt} from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css'
import 'dhtmlx-gantt/codebase/locale/locale_cn.js'  // 本地化
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_marker.js';
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_undo.js';
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_drag_timeline.js';
import 'dhtmlx-gantt/codebase/ext/dhtmlxgantt_tooltip.js';
import { reqCommonMsg } from '@/util/reqCommonMsg';

export default {
  name: 'gantt',
  props: {
    milestoneData: {
      type: Array,
      default() {
        return {}
      }
    },
    planTreeData: {
      type: Array,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      //更新中标识
      updating: false,
      //展开左侧
      isOpenLeft: true,
      zoomInOutModel: 2,
      viewModel: 1,
      tasks: {
        data: [],
        links: [{ id: 1, source: 1, target: 2, type: '0' }]
      },
      loading: false,
      data:[],
      
      group: 'plan',
      
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: [],
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    }
  },
  watch: {
    milestoneData: {
      handler(newValue, oldValue) {
        this.handleTaskData(this.viewModel);
      },
      deep: true
    },
  },
  methods: {
    
    /**
     * 加工数据
     */
    handleTaskData(viewModel){
      this.viewModel=viewModel;
      if(viewModel == 1){
        this.byMilestone();
      }
      else{
        this.byMPlantree();
      }
    },
    /**
     * 加工数据 按计划条目展示
     */
    byMPlantree(){
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading'
      });
      this.tasks.data = [];
      let taskData = [];
      let linkData = [];
      // 第一层
      this.planTreeData.forEach(element => {
        taskData.push({
          id: element.id,
          milestone: element.milestoneName,
          iterationName: element.iterationName,
          text: element.planName,
          start_date: element.planBeginDate,
          progress: parseFloat(element.progress / 100),
          duration: parseInt(element.planInvestmentTime),
          personName: element.respsbltPersonName,
          isMileStone: false,
          dataSign: element.dataSign,
          open: true
        });
        if(element.prevPlanId){
          linkData.push({
            id: element.id,
            source: element.prevPlanId,
            target: element.id,
            type: '0'
          });
        }
        // 第二层
        if(element.children && element.children.length > 0){
          element.children.forEach(children0Elment => {
            taskData.push({
              id: children0Elment.id,
              milestone: children0Elment.milestoneName,
              iterationName: children0Elment.iterationName,
              text: children0Elment.planName,
              parent: element.id,
              start_date: children0Elment.planBeginDate,
              progress: parseFloat(children0Elment.progress / 100),
              duration: parseInt(children0Elment.planInvestmentTime),
              personName: children0Elment.respsbltPersonName,
              dataSign: children0Elment.dataSign,
              isMileStone: false,
              open: true
            });
            linkData.push({
              id: children0Elment.id,
              source: element.id,
              target: children0Elment.id,
              type: '1'
            }); 
            if(children0Elment.prevPlanId){
              linkData.push({
                id: children0Elment.id,
                source: children0Elment.prevPlanId,
                target: children0Elment.id,
                type: '0'
              });
            }
            // 第三层
            if(children0Elment.children && children0Elment.children.length > 0){
              children0Elment.children.forEach(children1Elment => {
                taskData.push({
                  id: children1Elment.id,
                  milestone: children1Elment.milestoneName,
                  iterationName: children1Elment.iterationName,
                  text: children1Elment.planName,
                  parent: children0Elment.id,
                  start_date: children1Elment.planBeginDate,
                  progress: parseFloat(children1Elment.progress / 100),
                  duration: parseInt(children1Elment.planInvestmentTime),
                  personName: children1Elment.respsbltPersonName,
                  dataSign: children1Elment.dataSign,
                  isMileStone: false,
                  open: true
                });
                linkData.push({
                  id: children1Elment.id,
                  source: children0Elment.id,
                  target: children1Elment.id,
                  type: '1'
                });
                if(children1Elment.prevPlanId){
                  linkData.push({
                    id: children1Elment.id,
                    source: children1Elment.prevPlanId,
                    target: children1Elment.id,
                    type: '0'
                  });
                }
                // 第四层
                if(children1Elment.children && children1Elment.children.length > 0){
                  children1Elment.children.forEach(children2Elment => {
                    taskData.push({
                      id: children2Elment.id,
                      milestone: children2Elment.milestoneName,
                      iterationName: children2Elment.iterationName,
                      text: children2Elment.planName,
                      parent: children1Elment.id,
                      start_date: children2Elment.planBeginDate,
                      progress: parseFloat(children2Elment.progress / 100),
                      duration: parseInt(children2Elment.planInvestmentTime),
                      personName: children2Elment.respsbltPersonName,
                      dataSign: children2Elment.dataSign,
                      isMileStone: false,
                      open: true
                    });
                    linkData.push({
                      id: children2Elment.id,
                      source: children1Elment.id,
                      target: children2Elment.id,
                      type: '1'
                    });
                    if(children2Elment.prevPlanId){
                      linkData.push({
                        id: children2Elment.id,
                        source: children2Elment.prevPlanId,
                        target: children2Elment.id,
                        type: '0'
                      });
                    }
                    // 第五层
                    if(children2Elment.children && children2Elment.children.length > 0){
                      children2Elment.children.forEach(children3Elment => {
                        taskData.push({
                          id: children3Elment.id,
                          milestone: children3Elment.milestoneName,
                          iterationName: children3Elment.iterationName,
                          text: children3Elment.planName,
                          parent: children2Elment.id,
                          start_date: children3Elment.planBeginDate,
                          progress: parseFloat(children3Elment.progress / 100),
                          duration: parseInt(children3Elment.planInvestmentTime),
                          personName: children3Elment.respsbltPersonName,
                          dataSign: children3Elment.dataSign,
                          isMileStone: false,
                          open: true
                        });
                        linkData.push({
                          id: children3Elment.id,
                          source: children2Elment.id,
                          target: children3Elment.id,
                          type: '1'
                        });
                        if(children3Elment.prevPlanId){
                          linkData.push({
                            id: children3Elment.id,
                            source: children3Elment.prevPlanId,
                            target: children3Elment.id,
                            type: '0'
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
      gantt.clearAll();
      this.tasks.data = taskData;
      this.tasks.links = linkData;
      setTimeout(() => {
        this.genGantt();
        loading.close();
      }, 500); 
    },
    /**
     * 加工数据 按里程碑展示的甘特图
     */
    byMilestone(){ 
      gantt.clearAll();
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        customClass: 'loadingStyle'
      });
      this.tasks.data = [];
      let taskData = [];
      let linkData = [];
      this.milestoneData.forEach(element => {
        taskData.push({
          id: element.id,
          text: element.milestoneName,
          milestone: element.milestoneName,
          iterationName: element.iterationName,
          start_date: element.planBeginDate,
          end_date: element.planEndDate,
          progress: parseFloat(element.progress / 100),
          duration: this.$toolUtil.getWorkday(element.planBeginDate,element.planEndDate),
          personName: '',
          dataSign: element.dataSign,
          isMileStone: true,
          open: true
        });
        //处理里程碑
        if(element.flagName){
          console.log('element.flagStyleName==',element.flagStyleName);
          gantt.addMarker({
            start_date: new Date(element.planEndDate),
            css: element.flagStyleName || 'today',
            text: element.flagName,
            title: element.flagName
          }); 
        }
        //处理计划
        if(element.planList && element.planList.length > 0){
          element.planList.forEach(planListElment => {
            taskData.push({
              id: planListElment.id,
              milestone: planListElment.milestoneName,
              iterationName: planListElment.iterationName,
              text: planListElment.planName,
              parent: element.id,
              start_date: planListElment.planBeginDate,
              progress: parseFloat(planListElment.progress / 100),
              duration: parseInt(planListElment.planInvestmentTime),
              personName: planListElment.respsbltPersonName,
              dataSign: planListElment.dataSign,
              isMileStone: false,
              open: true
            });

            linkData.push({
              id: planListElment.id,
              source: element.id,
              target: planListElment.id,
              type: '1'
            });
            if(planListElment.prevPlanId){
              linkData.push({
                id: planListElment.id,
                source: planListElment.prevPlanId,
                target: planListElment.id,
                type: '0'
              });
            }
          });
        }
      });
      this.tasks.data = taskData;
      this.tasks.links = linkData;
      setTimeout(() => {
        this.genGantt();
        loading.close();
      }, 500); 
    },
    /**
     * 打开左侧表格
     */
    openLeftGrid(){
      this.isOpenLeft = !this.isOpenLeft;
      gantt.config.show_grid = this.isOpenLeft; //是否显示左侧表格
      gantt.render();
    },
    undo(){
      gantt.undo();
    },
    redo(){
      gantt.redo();
    },
    resize(){ 
      // 时间线
      var date_to_str = gantt.date.date_to_str(gantt.config.task_date);
      var today = new Date('2021-05-22');
      gantt.addMarker({
        start_date: new Date('2021-05-22'),
        css: 'today',
        text: '今天',
        title: '今天: ' + date_to_str(today)
      }); 
    },
    startZoomIn(){
      this.zoomInOutModel = 1;
      gantt.config.scale_unit = 'month';
      gantt.config.subscales = [{unit: 'week', format: '第%W周'}];
      gantt.render();
    },
    startZoomOut(){
      this.zoomInOutModel = 2;
      gantt.config.scale_unit = 'month';
      gantt.config.date_scale = '%F, %Y';
      gantt.config.subscales = [{ unit: 'week', step: 1, date: '第%W周' },{ unit: 'day', step: 1, date: '%j-周%D' }];
      gantt.render();
    },
    exportToPDF(){
      gantt.exportToPDF({
        name: 'mygantt.pdf'
      });
    },
    /**
     * 实例化甘特图
     */
    genGantt() {
      let _this = this;
      console.log('milestoneData==',this.milestoneData);
      var usageMap =  [
        { key: 1, label: 'wood', unit: 'box' },
        { key: 2, label: 'water', unit: 'liter' },
        { key: 3, label: 'grain', unit: 'lbs',
          options: [
            { key: 1, label: '10' },
            { key: 2, label: '20' },
            { key: 3, label: '30' }
          ]
        }
      ];
      gantt.serverList('people', [
        {key: 6, label: 'John'},
        {key: 7, label: 'Mike'},
        {key: 8, label: 'Anna'},
        {key: 9, label: 'Bill'},
        {key: 10, label: 'Floe'}
      ]);
      var roomsMap =  [
        { key: 1, label: 'room 1', unit: 'hours' },
        { key: 2, label: 'room 2', unit: 'hours' },
        { key: 3, label: 'room 3', unit: 'hours' }
      ];
      gantt.locale={
        date: {
          month_full: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
          month_short: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          day_full: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
          day_short: ['日', '一', '二', '三', '四', '五', '六']
        },
        labels: {
          dhx_cal_today_button: '今天',
          day_tab: '日',
          week_tab: '周',
          month_tab: '月',
          new_event: '新建日程',
          icon_save: '保存1',
          icon_cancel: '关闭',
          icon_details: '详细1',
          icon_edit: '编辑',
          icon_delete: '删除',
          confirm_closing: '请确认是否撤销修改!', //Your changes will be lost, are your sure?
          confirm_deleting: '是否删除日程?',
          section_description: '描述:',
          section_time: '时间范围:',
          section_priority: '类型:',
          section_personName : '姓名',
          /* grid columns */

          column_text: '任务名',
          column_start_date: '开始时间',
          column_duration: '持续时间',
          column_add: '',

          /* link confirmation */

          link: '关联',
          confirm_link_deleting: '将被删除',
          link_start: ' (开始)',
          link_end: ' (结束)',

          type_task: '任务',
          type_project: '项目',
          type_milestone: '里程碑',

          minutes: '分钟',
          hours: '小时',
          days: '天',
          weeks: '周',
          months: '月',
          years: '年'
        }
      };
      gantt.config.xml_date='%Y-%m-%d %H:%i';

      // // 在时间线上增加一行年份显示
      // gantt.config.subscales = [
      //   {
      //     unit: 'year',
      //     step: 1,
      //     date: '%Y'
      //   }
      // ];
      // gantt.init(this.$refs.gantt);
      // gantt.parse(this.$props.tasks);
      // gantt.config.columns = [
      //     { name: "text", label: "项目", tree: true, width: "*" },
      //     { name: "personName", label: "负责人", align: "center" }
      //   ];
      gantt.config.columns=[
        {name: 'wbs', label: 'WBS编号',  width: 10, align: 'left', template: gantt.getWBSCode},
        {name:'text', label:'计划名称',  align: 'left' ,tree:true, min_width:200 , resize: true },
        {name: 'milestone', label: '里程碑', align: 'center', width:50 , resize: true, template: function (obj) {
          return '<font style="color:#0b8db4; font-weight:bold;">'+obj.milestone+'</font>'; // 通过 template 回调可以指定返回内容值
        },},
        {name:'start_date', label:'开始时间', align: 'center' , resize: true },
        {name:'end_date', label:'结束时间', align: 'center' , resize: true },
        {name:'duration',   label:'耗时(天)',   align: 'center' , resize: true },
        {name:'progress',   label:'进度',  width:50 , align: 'center' , resize: true, template: function (obj) {
          if (Math.round(obj.progress * 100) == 100){
            return '<font style="font-weight:bold;color:#0b8d00;">'+ Math.round(obj.progress * 100)+'%</font>'; // 通过 template 回调可以指定返回内容值
          }
          else if (Math.round(obj.progress * 100) == 0){
            return '<font style="font-weight:bold;">'+ Math.round(obj.progress * 100)+'%</font>'; // 通过 template 回调可以指定返回内容值
          }
          else if (Math.round(obj.progress * 100) > 1){
            return '<font style="font-weight:bold;color:blue;">'+ Math.round(obj.progress * 100)+'%</font>'; // 通过 template 回调可以指定返回内容值
          }
        },},
        {name: 'personName', label: '负责人', align: 'center',  min_width:100 , resize: true, template: function (obj) {
          return '<font style="font-weight:bold;">'+obj.personName+'</font>'; // 通过 template 回调可以指定返回内容值
        },},
        //{name:'add',        label:'',  resize: true }
      ];

      gantt.locale.labels['section_priority'] = 'Priority';
      //gantt.i18n.setLocale('cn');
      gantt.config.autofit = true;
      gantt.config.select_task = true; // 任务是否可以点击选中
      gantt.config.smart_scales = true; // 仅仅渲染在屏幕可见的那部分时间轴。在处理时间轴非常长的时候，可以提升性能
      gantt.config.duration_unit = 'day' // 工期计算的基本单位
      gantt.config.drag_links = false;

      //gantt.config.drag_move = true; //不能拖动
      gantt.config.grid_width = 750;
      gantt.config.grid_resize = true; 
      gantt.config.grid_resizer_attribute = 'gridresizer';
      gantt.config.grid_resizer_column_attribute = 'column_index'
      gantt.config.task_date = '%Y-%m-%d %H:%s';
      gantt.config.time_picker = '%H:%s';
      gantt.config.step = 1; 
      gantt.config.scale_unit = 'month';
      gantt.config.date_scale = '%F, %Y';
      if(this.zoomInOutModel == 1){
        gantt.config.subscales = [{unit: 'week', format: '第%W周'}];
      }
      else{
        gantt.config.subscales = [{ unit: 'week', step: 1, date: '第%W周' },{ unit: 'day', step: 1, date: '%j, 周%D' }];
      }
      // 设置时间轴起始时间
      gantt.config.start_date = new Date('2021-01-01');
      gantt.config.end_date = new Date('2025-07-21');
      //当右侧不止显示年份时，可以添加展示月日，添加一个就加一行 
      gantt.config.scale_height = 80; 
      //甘特图右侧表头的高度
      gantt.config.min_column_width = 50; 
      //下面日期的宽度，会随时间长短宽度变化。但是设置最小宽度后，当时间跨度到达一定长度，就会展示最小宽度
      gantt.config.work_time = true; 
      //跳过节假日：比如你选择的包含周六日，他会自动延长时间或者缩短，延长或者缩短是因为包含节假日，要增加或者减少天数。
      gantt.config.correct_work_time = true; 
      //处理节假日
      var holidays = [//USA, DC holidays
        new Date(2021, 4, 1),
        new Date(2021, 4, 20),
        new Date(2021, 4, 17),
        new Date(2014, 3, 16),
        new Date(2014, 4, 26),
        new Date(2014, 6, 4),
        new Date(2014, 8, 1),
        new Date(2014, 9, 13),
        new Date(2014, 10, 11),
        new Date(2014, 10, 27),
        new Date(2014, 11, 25)
      ];

      for(var i=0; i < holidays.length; i++){
        gantt.setWorkTime({
          date:holidays[i],
          hours:false
        });
      }

      //gantt.config.duration_unit = "hour";  以小时为单位
      // gantt.templates.task_cell_class = function(task, date){
      //   if(is_selected_column(date)){
      //     return 'highlighted-column';
      //   }
      //   else if(!gantt.isWorkTime(date)){
      //     return 'week_end';
      //   }
      //   else{
      //     return '';
      //   }
      // };


      // gantt.templates.grid_row_class = function(item) {
      //   if (item.progress  == 100) return 'red';
      //   if (item.progress > 0) return 'green';
      // };
      // gantt.templates.task_row_class = function(start_date, end_date, item) {
      //   if (item.progress  == 0) return 'red';
      //   if (item.progress > 0) return 'green';
      // };

      gantt.templates.grid_row_class = function(start, end, item){
        return item.$level==0?'gantt_project':''
      }
      gantt.templates.task_row_class = function(start, end, item){
        return item.$level==0?'gantt_project':''
      }
      gantt.templates.task_class = function(start, end, item){
        return item.$level==0?'gantt_project':''
      }
      

      gantt.config.inherit_scale_class = true; 
      gantt.config.autofit = true;
      gantt.config.autoscroll = true;
      //gantt.config.autosize = 'xy';
      gantt.config.autosize_min_width = 800;
      gantt.config.start_on_monday = true; // 第一天将变为周日

      gantt.config.show_quick_info = true;   
      //gantt.config.min_grid_column_width = 100; //左侧表格列的最小宽度
      gantt.config.details_on_create = true; //显示新增对话框
      gantt.config.details_on_dblclick = false;
  
      gantt.config.autoscroll_speed = 50
      gantt.locale.labels['complete_button'] = 'Complete';

      gantt.config.redo = true;
      gantt.config.undo = true;
      gantt.config.readonly=false;
      //gantt.config.placeholder_task = true;
      gantt.config.sort = false;
      //拖动排序
      gantt.config.order_branch = false;
      gantt.config.order_branch_free = false;
      gantt.config.scroll_on_click= true; //点击显示对应的甘特图
      gantt.config.show_grid = true; //是否显示左侧表格
      //var textEditor = {type: "text", map_to: "text"};
      //var dateEditor =  {type: "date", map_to: "start_date", min: new Date(2018, 0, 1), max: new Date(2023, 0, 1)};
    
      // gantt.config.columns = [
      //     {name: "text", label: "Task name", tree: true, width: "*", editor: textEditor},
      //     {name: "start_date", label: "Start time", align: "center", editor: dateEditor},
      //     {name:"add",        label:"" }
      // ];
      // gantt.config.lightbox.sections = [
      //   {name:"description", height:72, map_to:"text", type:"textarea",focus:true},
      //   {name:"personName", height:72, type:"textarea", map_to:"personName", options:[{ key: 1, lable: 'demo'},{ key: 2, lable: 'demo2'}]}

      // ];
      gantt.config.lightbox.sections = [
        { name: 'description', height: 38, map_to: 'text', type: 'textarea', focus: true },
        {
          name: 'priority', height: 22, map_to: 'priority', type: 'select', options: [
            {key: 1, label: '高'},
            {key: 2, label: '中'},
            {key: 3, label: '低'}
          ]
        },
        { name: 'time', type: 'duration', map_to: 'auto' ,time_format:['%Y','%m','%d',  '%H:%i']},
        {
          name: 'resources', type: 'resources', map_to: 'usage', options: usageMap
        },
        {
          name: 'rooms', type: 'resources', map_to: 'rooms', options: roomsMap
        },
        {name:'owner',height:60, type:'multiselect', options:gantt.serverList('people'), map_to:'personName'},

      ];
      gantt.config.undo_actions = {
        update:'update',
        remove:'remove', // remove an item from datastore
        add:'add'
      };

      //gantt.config.drag_resize = false; //进度条不可拖动
 
      //将今天线划出
      // var date_to_str = gantt.date.date_to_str(gantt.config.task_date);
      // var today = new Date();
      // gantt.addMarker({
      //   start_date: today,
      //   css: 'today',
      //   text: '今天',
      //   title:'今天: '+ date_to_str(today)
      // }); 


      gantt.templates.task_text=function(start,end,task) {
        return '<b style=\'text-align:left;\'>计划名称:</b> ' + task.text +' <span style=\'text-align:left;\'>' +'完成计划：'+ Math.round(task.progress * 100) + '% </span>';
      };
      gantt.config.tooltip_hide_timeout = 2000;
      gantt.templates.tooltip_text = function(start, end, task) {
        var tipStr = '<span style=\'font-weight:bold\'>所属迭代：</span>'+task.iterationName+'<br>';
        tipStr += '<span style=\'font-weight:bold\'>计划名称：</span>'+task.text+'<br>';
        tipStr += '<span style=\'font-weight:bold\'>开始时间：</span>'+_this.$toolUtil.formatDate(task.start_date)+'<br>';
        tipStr += '<span style=\'font-weight:bold\'>结束时间：</span>'+_this.$toolUtil.formatDate(task.end_date)+'<br>';
        tipStr += '<span style=\'font-weight:bold\'>完成进度：</span>'+ Math.round(task.progress * 100)+'% <br>';
        tipStr += '<span style=\'font-weight:bold\'>负 责 人：</span>'+task.personName;
        return tipStr;
      };
      gantt.templates.leftside_text = function(start, end, task){
        return task.duration + ' 天';
      };
      var selected_column = null;
      
      gantt.attachEvent('onScaleClick', function (e, date) {
        selected_column = date;
        var pos = gantt.getScrollState();
        gantt.render();
        gantt.scrollTo(pos.x, pos.y);
      });

      //===高亮列开始
      function is_selected_column (column_date){
        if(selected_column && column_date.valueOf() == selected_column.valueOf()){
          return true;
        }
        return false;
      }
      gantt.templates.scale_cell_class = function (date) {
        if(is_selected_column(date))
          return 'highlighted-column';
      };
      gantt.templates.task_cell_class = function (item, date) {
        if(!gantt.isWorkTime(date, 'day')){
          return ('no_work_hour');
        }
        else if(is_selected_column(date)){
          return 'highlighted-column';
        }
        else{
          return '';
        }
      };
      //====高亮列结束
      //gantt.message("Click on any date in a scale to select a column");

      //初始化
      gantt.init(this.$refs.gantt);
      gantt.parse(this.tasks);
      //gantt.showLightbox(1);

      gantt.attachEvent('onTaskSelected', (id) => {
        console.log('111tesdt=-====id==',id);
      // let task = gantt.getTask(id);
      // this.$emit('task-selected', task);
      });

      // gantt.attachEvent('onAfterTaskDrag', function(id, mode, e){
      //   console.log('onAfterTaskDrag=-====id==',id,mode,e);
      //   //any custom logic here
      // });
      gantt.attachEvent('onAfterTaskUpdate', function(id,item){
        _this.taskUpdating(item);
      });

      gantt.attachEvent('onTaskIdChange', (id, new_id) => {
        if (gantt.getSelectedId() == new_id) {
          let task = gantt.getTask(new_id);
          this.$emit('task-selected', task);
        }
      });

      gantt.attachEvent('onTaskDblClick', function(id, e) {
        let planData = {};
        _this.milestoneData.forEach(element => {
          if(element.planList && element.planList.length > 0){
            element.planList.forEach(planElement => {
              if(planElement.id == id){
                planData = planElement;
              }
            });
          }
        });
        _this.openDetail(planData);
      });
    },
    /**
     * 更新任务
     */
    taskUpdating(item){
      if(!this.updating){
        this.updating = true;
        setTimeout(() => {
          console.log('==item=',item);
          this.updating = false;
          if(item.isMileStone){
            this.updateMilestone(item);
          }
          else {
            this.updatePlan(item)
          }
        }, 100);
      }
    },
    /**
     * 修改里程碑
     */
    updateMilestone(item){
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading'
      });
      this.reqParams.singleBody = {
        id: item.id,
        progress: Math.round(item.progress * 100),
        planBeginDate: this.$toolUtil.formatDate(item.start_date),
        planEndDate: this.$toolUtil.formatDate(item.end_date),
        dataSign: item.dataSign
      }
      console.log('==body:',this.reqParams.singleBody);
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizPlanMilestone(this.commonData).then(res => {
        item.dataSign = res.data.body.singleBody.dataSign;
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
        this.$emit('loadMilestone','');
        loading.close();
      }, error => {
        loading.close();
      });
    },

    /**
     * 修改计划
     */
    updatePlan(item) {
      const loading = this.$loading({
        lock: true,
        text: '处理中...',
        spinner: 'el-icon-loading'
      });
      this.reqParams.singleBody = {
        id: item.id,
        progress: Math.round(item.progress * 100),
        planBeginDate: this.$toolUtil.formatDate(item.start_date),
        planEndDate: this.$toolUtil.formatDate(item.end_date),
        planInvestmentTime: item.duration,
        dataSign: item.dataSign
      }
      this.commonData = reqCommonMsg(this.reqParams)
      updateBizPlanManage(this.commonData).then(res => {
        item.dataSign = res.data.body.singleBody.dataSign;
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '保存成功!'
        });
        this.$emit('loadPlanList','');
        loading.close();
      }, error => {
        loading.close();
      });
    },
    /**
     * 打开添加计划对话框
     */
    openAddDialog(){
      console.log('添加计划');
      let plan={
        id: this.milestoneData.id,
        milestoneName: this.milestoneData.milestoneName
      }
      this.$emit('openAddPlanDialog',plan);
    },
    /**
     * 打开计划明细
     */
    openDetail(row){
      this.$emit('openUpdatePlanDialog',row);
    },
  },
  mounted() {
    this.genGantt();
  }
}
</script>
 
<style>
  .ganttContainer {
    height: 100% !important;
    width: 100% !important;
    margin: 0;
    padding: 0;
  }
  .container {
    height: 85vh;
    width: 100%;
  }
  .loadingStyle{
    z-index: 10000 !important;
  }
  .gantt_task_progress{
    text-align:left;
    padding-left:10px;
      box-sizing: border-box;
    color:white;
    font-weight: bold;
  }
	.highlighted-column {
		background-color:#fff3a1;
	}
	.gantt_task_scale .gantt_scale_cell{
		cursor: default;
	}
	.gantt_task_scale .gantt_scale_cell.highlighted-column {
		color: #454545;
		font-weight: bold;
	}
  .gantt_task_cell.week_end{
		background-color: #EFF5FD;
	}
	.gantt_task_row.gantt_selected .gantt_task_cell.week_end{
		background-color: #F8EC9C;
	}
  .gantt_tooltip{
    z-index: 10000 !important;
  }

    .red .gantt_cell, .odd.red .gantt_cell,
    .red .gantt_task_cell, .odd.red .gantt_task_cell{
        background-color: #FDE0E0;
    }
    .green .gantt_cell, .odd.green .gantt_cell,
    .green .gantt_task_cell, .odd.green .gantt_task_cell {
        background-color: #BEE4BE;
    }
  
  .gantt_task_cell.no_work_hour{
		background-color: #F5F5F5;
	}
	.gantt_task_row.gantt_selected .gantt_task_cell.no_work_hour{
		background-color: #F8EC9C;
	}
  /* mark线颜色样式 */
  .red_line{
    background-color: #c00101;
  }
  .pink_line{
    background-color: #d36f6f;
  }
  .blue_line{
    background-color: #3f7fdf;
  }
  .dark_blue_line{
    background-color: #0010a1;
  }
  
  .black_line{
    background-color: #000000;
  }
  .green_line{
    background-color: #7fb47e;
  }
  .dark_green_line{
    background-color: #0ba308;
  }
  .orange_line{
    background-color: #d47d0a;
  }
  .yellow_line{
    background-color: #acaf05;
  }
  .purple_line{
    background-color: #6807a0;
  }
  @import "~dhtmlx-gantt/codebase/dhtmlxgantt.css";
  /* @import "~dhtmlx-gantt/codebase/skins/dhtmlxgantt_meadow.css"; */
</style>